﻿// QuartZ Cron表达式参考https://www.cnblogs.com/free-dom/p/5801917.html
/*
QuartZ与springcron区别 
-----------------------------------------------------------------------------------
字段 	        		 |QuartZ         		 	      				|springcron
-----------------------------------------------------------------------------------
星期 					 1-7，周日=1，周一=2……，                           0-7，周一=1，周二=2，0=7=周日
特殊字符 			
    秒（Seconds）        ：【, - * / 4个字符】								【, - * / 4个字符】	
	分（Minutes）	    ：【, - * / 4个字符】								【, - * / 4个字符】
    小时（Hours）        ：【, - * / 4个字符】								【, - * / 4个字符】
    日期（DayofMonth）   ：【, - * / ? L C W  8个字符】					    【, - * / ? 5个字符】
    月份（Month） 	    ：【, - * / 4个字符】								【, - * / 4个字符】	
    星期（DayofWeek）    ：【, - * / ? L C #  8个字符】					    【, - * / ? 5个字符】
    年(可选)（Year）     ：【, - * / 4个字符】								 不支持	
------------------------------------------------------------------------------------ */
/*!
 * cronGen v1.0.0
 */
(function ($) {
    
    var inputElement;
    var displayElement;
    var valueShowElement;
    var execTimesUrl;
    var type_quartz = "quartz";
    var type_springcron = "springcron";
    cronIndex = 0;
    $.fn.extend({
        cronGen: function (options) {
            if (options == null) {
              options = {};
            }
            options = $.extend({}, $.fn.cronGen.defaultOptions, options);
            execTimesUrl = options.execTimesUrl; // 执行时间url
            var cronContainer = $("<div/>", { id: "CronContainer"}); //容器
            
            //类型选择区
            var typeDiv = $("<div/>", { id: "CronGenTypeDiv", "class":"crongendiv"});
            var CronGenTypeInputE0 = $('<span class="type_quartz"><input type="radio" name="CronGenTypeInput" class="shield-input" value="'+ type_quartz +'" checked="'+ (options.type==type_quartz) +'" />&nbsp;Quartz</span>'); //类型
            var CronGenTypeInputE1 = $('<span class="type_springcron"><input type="radio" name="CronGenTypeInput" class="shield-input" value="'+ type_springcron +'" checked="'+ (options.type==type_springcron) +'" />&nbsp;SpringCron</span>'); //类型
            typeDiv.append(CronGenTypeInputE0);
            typeDiv.append(CronGenTypeInputE1);
            
            
            //创建表达式及释义区
            var valueDiv = $("<div/>", { id: "CronGenValueDiv", "class":"crongendiv"});
            var valueInputDiv = $("<div/>", { id: "CronGenValueInputDiv"});
            valueInputDiv.html("<span>表达式：</span>");
            var CronGenValueInput = $('<input/>', { 'type': 'text', id: "CronGenValueInput", "class":"shield-input" });
            valueInputDiv.append(CronGenValueInput);
            valueDiv.append(valueInputDiv);
            valueDiv.append('<div class="CronGenValueExpDiv"><span>说　明：</span><span class="CronGenValueExplanation" style="width:460px; margin-left:0px;"></span>' +
            		'<span class="CronGenValueShow CronGenValueShowSecond"></span><span class="CronGenValueShow CronGenValueShowMinute"></span>' +
            		'<span class="CronGenValueShow CronGenValueShowHour"></span><span class="CronGenValueShow CronGenValueShowDayOfMonth"></span>' +
            		'<span class="CronGenValueShow CronGenValueShowMonth"></span><span class="CronGenValueShow CronGenValueShowDayOfWeek"></span>' +
            		'<span class="CronGenValueShow CronGenValueShowYear"></span></div>');
            valueShowElement = CronGenValueInput;
            
            // 内容区，即input选择区
            var mainDiv = $("<div/>", { id: "CronGenMainDiv"});
            
            var topMenu = $("<ul/>", { "class": "nav nav-tabs", id: "CronGenTabs" });
            $('<li/>', { 'class': 'active' }).html($('<a id="SecondlyTab" href="#Secondly">秒</a>')).appendTo(topMenu);
            $('<li/>').html($('<a id="MinutesTab" href="#Minutes">分钟</a>')).appendTo(topMenu);
            $('<li/>').html($('<a id="HourlyTab" href="#Hourly">小时</a>')).appendTo(topMenu);
            $('<li/>').html($('<a id="DailyTab" href="#Daily">日</a>')).appendTo(topMenu);
            $('<li/>').html($('<a id="MonthlyTab" href="#Monthly">月</a>')).appendTo(topMenu);
            $('<li/>').html($('<a id="WeeklyTab" href="#Weekly">周</a>')).appendTo(topMenu);
            //quartz支持，其他不支持
            $('<li/>').addClass("cron_quartz_show").html($('<a id="YearlyTab" href="#Yearly">年</a>')).appendTo(topMenu);
           
            $(topMenu).appendTo(mainDiv);

            //create what's inside the tabs
            var container = $("<div/>", { "class": "container-fluid" });
            var row = $("<div/>", { "class": "row-fluid" });
            var span12 = $("<div/>", { "class": "span12" });
            var tabContent = $("<div/>", { "class": "tab-content"});


            //秒 页签
            var secondsTab = $("<div/>", { "class": "tab-pane active", id: "Secondly" });
            
            var seconds1 = createEveryTimeHtml("second", 1); //每xx
            seconds1.appendTo(secondsTab);
            
            var seconds2 = createCycleHtml("second", 2); // 范围
            seconds2.appendTo(secondsTab);
            
            var seconds3 = createFrequencyHtml("second", 3); // 周期
            seconds3.appendTo(secondsTab);
            
            var seconds4 = createAppointHtml("second", 4); // 指定
            seconds4.appendTo(secondsTab);
            
            $("<input/>",{type : "hidden", id : "secondHidden"}).appendTo(secondsTab);
            $(secondsTab).appendTo(tabContent);
            
            //分钟 页签
            var minutesTab = $("<div/>", { "class": "tab-pane", id: "Minutes" });
            
            var minutes1 = createEveryTimeHtml("min", 1); //每xx
            $(minutes1).appendTo(minutesTab);
            
            var minutes2 = createCycleHtml("min", 2); //范围
            minutes2.appendTo(minutesTab);
            
            var minutes3 = createFrequencyHtml("min", 3); // 周期
            minutes3.appendTo(minutesTab);
            
            var minutes4 = createAppointHtml("min", 4); // 指定 
            $(minutes4).appendTo(minutesTab);
            
            $("<input/>",{type : "hidden", id : "minHidden"}).appendTo(minutesTab);
            $(minutesTab).appendTo(tabContent);
            
            //小时 页签
            var hourlyTab = $("<div/>", { "class": "tab-pane", id: "Hourly" });

            var hourly1 = createEveryTimeHtml("hour", 1); //每xx
            $(hourly1).appendTo(hourlyTab);
            
            var hourly2 = createCycleHtml("hour", 2); //范围;
            hourly2.appendTo(hourlyTab);
            
            var hourly3 = createFrequencyHtml("hour", 3); //周期
            hourly3.appendTo(hourlyTab);
            
            var hourly4 = createAppointHtml("hour", 4); // 指定 
            $(hourly4).appendTo(hourlyTab);
            
            $("<input/>",{type : "hidden", id : "hourHidden"}).appendTo(hourlyTab);
            $(hourlyTab).appendTo(tabContent);
            

            //天 页签
            var dailyTab = $("<div/>", { "class": "tab-pane", id: "Daily" });

            var daily1 = createEveryTimeHtml("day", 1); //每xx
            $(daily1).appendTo(dailyTab);
            
            var daily2 = createUnAppointHtml("day", 2); //不指定
            daily2.appendTo(dailyTab);
            
            var daily3 = createCycleHtml("day", 3); //范围;
            daily3.appendTo(dailyTab);
            
            var daily4 = createFrequencyHtml("day", 4); // 周期
            daily4.appendTo(dailyTab);
            //quartz支持
            var daily6 = $("<div/>",{"class":"line line_daily cron_quartz_show"});
            $("<input/>",{type : "radio", value : "5", id:"day_workDay", name : "day", 'class' : "input-radio"}).appendTo(daily6);
            
            var inputGroup = $("<div/>", {"class":"input-group "});
        	inputGroup.append('<span class="input-group-addon input-group-addon-l">每月</span>');
        	$("<input/>",{type : "text", id : "dayStart_2", value : "1", 'class' : "input-width"}).appendTo(inputGroup);
        	inputGroup.append('<span class="input-group-addon input-group-addon-r">号最近的那个工作日</span>');
        	
            inputGroup.appendTo(daily6);
            daily6.appendTo(dailyTab);
            
            //quartz支持，其他不支持
            var daily7 = $("<div/>",{"class":"line line_daily cron_quartz_show"});
            $("<input/>",{type : "radio", value : "6", id:"day_lastDay", name : "day", 'class' : "input-radio"}).appendTo(daily7);
            
            var inputGroup = $("<div/>", {"class":"input-group "});
            inputGroup.append('<span class="input-group-addon input-group-addon-l input-group-addon-r">每月最后一天</span>');
            inputGroup.appendTo(daily7);
            daily7.appendTo(dailyTab);
			
			//quartz支持，其他不支持
            var daily8 = $("<div/>",{"class":"line line_daily cron_quartz_show"});
            $("<input/>",{type : "radio", value : "8", id:"day_lastWorkDay", name : "day", 'class' : "input-radio"}).appendTo(daily8);
            
            var inputGroup = $("<div/>", {"class":"input-group "});
            inputGroup.append('<span class="input-group-addon input-group-addon-l input-group-addon-r">每月最后一个工作日</span>');
            inputGroup.appendTo(daily8);
            daily8.appendTo(dailyTab);
                        
            var daily4 = createAppointHtml("day", 7); // 指定 
            daily4.appendTo(dailyTab);
            
            $("<input/>",{type : "hidden", id : "dayHidden"}).appendTo(dailyTab);
            $(dailyTab).appendTo(tabContent);
            
            
            //月 页签
            var monthlyTab = $("<div/>", { "class": "tab-pane", id: "Monthly" });

            var monthly1 = createEveryTimeHtml("month", 1); //每xx
            $(monthly1).appendTo(monthlyTab);
            
//            无意义
//            var monthly2 = $("<div/>",{"class":"line line_monthly"});
//            $("<input/>",{type : "radio", value : "2", id:"month_unAppoint", name : "month"}).appendTo(monthly2);
//            $(monthly2).append("不指定");
//            $(monthly2).appendTo(monthlyTab);
            
            var monthly3 = createCycleHtml("month", 3); //范围;
            monthly3.appendTo(monthlyTab);
            
            var monthly4 = createFrequencyHtml("month", 4); // 周期
            monthly4.appendTo(monthlyTab);
            
            var monthly5 = createAppointHtml("month", 5); // 指定
            monthly5.appendTo(monthlyTab);
            
            $("<input/>",{type : "hidden", id : "monthHidden"}).appendTo(monthlyTab);
            $(monthlyTab).appendTo(tabContent);

            //周 页签
            var weeklyTab = $("<div/>", { "class": "tab-pane", id: "Weekly" });
            
            var weekly1 = createEveryTimeHtml("week", 1); //每xx
            $(weekly1).appendTo(weeklyTab);
            
            var weekly2 = createUnAppointHtml("week", 2); //不指定
            $(weekly2).appendTo(weeklyTab);
            
            var weekly3 = createCycleHtml("week", 3); //范围;
            $(weekly3).appendTo(weeklyTab);
            
            var weekly4 = $("<div/>",{"class":"line line_weekly cron_quartz_show"});
            $("<input/>",{type : "radio", value : "4", id:"week_weekOfDay", name : "week", 'class' : "input-radio"}).appendTo(weekly4);
            
            var inputGroup = $("<div/>", {"class":"input-group "});
        	inputGroup.append('<span class="input-group-addon input-group-addon-l">每月第</span>');
            $("<input/>",{type : "text", id : "weekStart_1", value : "1", 'class' : "input-width"}).appendTo(inputGroup);
            inputGroup.append('<span class="input-group-addon">个星期</span>');
            $("<input/>",{type : "text", id : "weekEnd_1", value : "1", 'class' : "input-width"}).appendTo(inputGroup);
            inputGroup.append('<span class="input-group-addon input-group-addon-r">&nbsp;</span>');
            
            inputGroup.appendTo(weekly4);
            weekly4.appendTo(weeklyTab);
            
            //quartz支持，其他不支持
            var weekly5 = $("<div/>",{"class":"line line_weekly cron_quartz_show"});
            $("<input/>",{type : "radio", value : "5", id:"week_lastWeek", name : "week", 'class' : "input-radio"}).appendTo(weekly5);
            
            var inputGroup = $("<div/>", {"class":"input-group "});
            inputGroup.append('<span class="input-group-addon input-group-addon-l">每月最后一个星期</span>');
            $("<input/>",{type : "text", id : "weekStart_2", value :"1", 'class' : "input-width"}).appendTo(inputGroup);
            inputGroup.append('<span class="input-group-addon input-group-addon-r">&nbsp;</span>');
            
            inputGroup.appendTo(weekly5);
            weekly5.appendTo(weeklyTab);
                        
            var weekly6 = createAppointHtml("week", 6); // 指定
            weekly6.appendTo(weeklyTab);
            
            $("<input/>",{type : "hidden", id : "weekHidden"}).appendTo(weeklyTab);
            $(weeklyTab).appendTo(tabContent);
            
            console.log("cronGen.js type:" + options.type)
            
            //年 页签
            var yearlyTab = $("<div/>", { "class": "tab-pane", id: "Yearly" });
            
            var yearly1 = createUnAppointHtml("year", 1); //不指定;
            yearly1.appendTo(yearlyTab);
            
            var yearly2 = createEveryTimeHtml("year", 2); //每xx;
            yearly2.appendTo(yearlyTab);
            
            //quartz支持，其他不支持
            var yearly3 = createCycleHtml("year", 3); //范围; //$("<div/>",{"class":"line line_yearly year-border cron_quartz_show"});
            yearly3.appendTo(yearlyTab);
            $("<input/>",{type : "hidden", id : "yearHidden"}).appendTo(yearlyTab); //值的隐藏域
            $(yearlyTab).appendTo(tabContent);

            
            $(tabContent).appendTo(span12);

            
            // 按钮
            var mainBtnDiv = $("<div/>", { "class": "CronGenBtnDiv"});
            var mainBtnDivHtml = '<div class="button-bg"><input type="button" ';
            if (options.submitBtnClass) { //默认"shield-btn"
            	mainBtnDivHtml += ' class="'+options.submitBtnClass+'"';
            }
            mainBtnDivHtml += ' id="submitbtn" value="确定"/></div>';
            if (execTimesUrl) { //最近几次运行时间
            	mainBtnDivHtml += '<div id="excuteTimeDiv"><span>后面6次的运行时间</span><div class="excuteTimeDivContent"><div/>';
            }
            mainBtnDiv.html(mainBtnDivHtml);

            $(span12).appendTo(row);
            $(row).appendTo(container);
            
            $(container).appendTo(mainDiv); //主内容各个选项区
            $(mainBtnDiv).appendTo(mainDiv); //主内容按钮区
            
            $(cronContainer).append(typeDiv); //类型
            $(cronContainer).append(valueDiv); //cron表达式
            $(cronContainer).append(mainDiv); //input
            
            if (options.type == type_quartz) {
            	$(cronContainer).find(".cron_quartz_show").show();
            } else {
            	$(cronContainer).find(".cron_quartz_show").hide();
            }
            //不显示类型选择时
            if (!options.showtype) {
            	typeDiv.hide();
            }
            
            var that = $(this);

            // Hide the original input
            that.hide();

            // Replace the input with an input group
            var inputGroupE = $("<div>").addClass("input-group input-group-cronGen");
            // Add an input
            var cronValReturnInputGE = $("<input>", { type: 'text', name:'cronval_show_'+cronIndex, placeholder: 'cron表达式...', value:$(that).val()}).addClass(options.showInputClass).val($(that).val());
            cronIndex++;
            valueShowElement.val($(that).val()); //自定义显示
            cronValReturnInputGE.appendTo(inputGroupE);
            cronValReturnInputGE.prop("readOnly", true); //只读
            // Add the button
            var selectBtnE = $(options.selectBtn);
            // Put button inside span
            var $s = $('<span style="' + options.inputGroupBtnStyle + '"></span>').addClass('input-group-btn');
            selectBtnE.appendTo($s);
            $s.appendTo(inputGroupE);

            $(this).before(inputGroupE);

            inputElement = that;
            displayElement = cronValReturnInputGE;
            // layer弹出框
            selectBtnE.on('click', function (e) {
            	e.preventDefault();
            	var winHeight = $(window).height();
            	var index = layer.open({
            		type: 1,
            		skin: 'layui-layer-rim', //加上边框
            		maxHeight : winHeight-14, //最大高度，只有当高度自适应时，设定才有效。
            		area: '600px', //宽度，高度自适应
            		title : "Cron选择器",
            		content: $(cronContainer).html()
            	});
            	valueShowElement = $("#CronGenValueInput");
            	valueShowElement.change(function() { //值改变的事件
            		var value = $(this).val();
            		// Update original control
                    inputElement.val(value); //返回值回写输入框（不可见）
                	displayElement.val(value); //显示输入框（可见）
                	if (execTimesUrl) { //最近几次运行时间
                		var type = $("input[name='CronGenTypeInput']:checked").val();
                		if (console && console.log) {
                			console.log("execTimesUrl==="+execTimesUrl);
                        }
    	            	//设置最近五次运行时间
    	            	$.ajax({
    	            		type: 'get',
    	            		url: execTimesUrl,
    	            		dataType: "json",
    	            		data: { "CronExpression" : valueShowElement.val(), type:type },
    	            		success: function (result) {
    	            			// success表示是否成功，message返回提示信息，object返回结果
    	            			if (result.success) {
    	            				var data = result.data;
    	            				if (data && data.length > 0) {
    	            					var strHTML = "<ul>";
    	            					for (var i = 0; i < data.length; i++) {
    	            						strHTML += "<li>" + data[i] + "</li>";
    	            					}
    	            					strHTML +="</ul>"
    	            					$(".excuteTimeDivContent").html(strHTML);
    	            				} else {
        	            				$(".excuteTimeDivContent").html(result.message);
        	            			}
                                } else {
    	            				$(".excuteTimeDivContent").html(result.message);
    	            			}
    	            		}
    	            	});
                	}
                	// 解释表达式 
                	var vals = value.replace(/  /g," ").split(" ");
                	if (vals.length >= 6) {
	                    showHtml = $.fn.cronGen.tools.explainCron(value); //中文解释
                		$(".CronGenValueExplanation").html(showHtml);
                    }
                });
            	valueShowElement.val(displayElement.val()).triggerHandler("change");
                
                $.fn.cronGen.tools.cronParse(inputElement.val());
                
                //绑定指定事件
                $.fn.cronGen.tools.initChangeEvent();
                
                $('#CronGenTabs a').click(function () { // 切换tab
                	$('#CronGenTabs li.active').removeClass("active");
                	$(this).closest("li").addClass("active");
                    $("#CronGenMainDiv").find(".tab-pane").removeClass("active");
                    $("#CronGenMainDiv").find(".tab-pane"+$(this).attr("href")).addClass("active");
                    //generate();
                    return false;
                });
                $("#CronGenMainDiv :input").not(":button,:submit").change(function () { // cron主内容区【各种页签】input改变
                    generate();
                });
                
                $("#CronGenTypeDiv :input[name='CronGenTypeInput']").change(function () { //切换类型
                    var val = $(this).val();
                    if (val == type_quartz) {
                    	$("#CronGenMainDiv").find(".cron_quartz_show")/*.not(".tab-pane")*/.show();
                    } else {
                    	var activeTab = $("ul#CronGenTabs li.active a").prop("id"); //获取当前活动页签id
                    	if ("YearlyTab" == activeTab) { //选中年，则往前推一个
                    		$("ul#CronGenTabs li a#WeeklyTab").click();
                    		
                        }
                    	$("#CronGenMainDiv").find(".cron_quartz_show").hide();
                    }
                    generate();
					$.fn.cronGen.tools.cronParse(inputElement.val());
                });
                
                $("#CronGenMainDiv #submitbtn").click(function () { //关闭窗口
                	layer.close(index);
                });
                
            });
            
            return;
        }
    });
    
   
    //创建不指定 html
    function createUnAppointHtml(tabType, radioVal){
    	 	
    	var seconds1 = $("<div/>", {"class":"line line_" + tabType + "ly"});
    	$("<input/>",{type : "radio", value : radioVal, id: tabType +"_unAppoint", name : tabType, 'class' : "input-radio"}).appendTo(seconds1);
    	
    	var inputGroup = $("<div/>",{"class":"input-group "});
    	inputGroup.append('<span class="input-group-addon input-group-addon-l input-group-addon-r">不指定</span>');
    	
    	inputGroup.appendTo(seconds1);
    	
    	return seconds1;
    }
    //创建每xxhtml
    function createEveryTimeHtml(tabType, radioVal){
    	var name = '';
    	var desp = '允许的通配符[, - * /]';
    	if(tabType=="second"){
    		name = '秒';
    	} else if(tabType=="min"){
    		name = '分钟';
    	} else if(tabType=="hour"){
    		name = '小时';
    	} else if(tabType=="day"){
    		name = '天';
    		desp = '允许的通配符[, - * /<span class="cron_quartz_show"> L W</span>]';
    	} else if(tabType=="month"){
    		name = '月';
    	} else if(tabType=="week"){
    		name = '周';
    		desp = '允许的通配符[, - * /<span class="cron_quartz_show"> L #</span>]';
    	} else if(tabType=="year"){
    		name = '年';
    		desp += ' 非必填';
    	}
    	
    	var seconds1 = $("<div/>", {"class":"line line_" + tabType + "ly"});
    	$("<input/>",{type : "radio", value : radioVal, id: tabType +"_everyTime", name : tabType, 'class' : "input-radio"}).appendTo(seconds1);
    	
    	var inputGroup = $("<div/>", {"class":"input-group "});
    	inputGroup.append('<span class="input-group-addon input-group-addon-l input-group-addon-r">每' + name + ' ' + desp + '</span>');
    	
    	inputGroup.appendTo(seconds1);
    	
    	return seconds1;
    }
    // 创建范围html
    function createCycleHtml(tabType, radioVal){
    	var namePrefix = ""; //前缀
    	var nameSuffix = ""; //后缀
    	var start=1, end=2;
    	if(tabType=="second"){
    		nameSuffix = "秒";
    	} else if(tabType=="min"){
    		nameSuffix = "分";
    	} else if(tabType=="hour"){
    		nameSuffix = "点";
    	} else if(tabType=="day"){
    		nameSuffix = "号";
    	} else if (tabType == "month") {
    		nameSuffix = "月";
    	} else if (tabType == "week") {
    		namePrefix = "星期";
    	} else if (tabType == "year") {
    		nameSuffix = "年";
    		var nowDate = new Date();
    		start = nowDate.getFullYear();
    		end = start + 10;
    	}
    	
    	var seconds2 = $("<div/>", {"class":"line line_"+tabType+"ly "});
    	$("<input/>",{type : "radio", value : radioVal, id: tabType +"_cycle",  name : tabType, 'class' : "input-radio"}).appendTo(seconds2);
    	
    	var inputGroup = $("<div/>", {"class":"input-group "});
    	inputGroup.append('<span class="input-group-addon input-group-addon-l">周期 从' + namePrefix + '</span>');
    	$("<input/>",{type : "text", id : tabType +"Start_0", value : start, 'class' : "input-width"}).appendTo(inputGroup);
    	inputGroup.append('<span class="input-group-addon">-</span>');
    	$("<input/>",{type : "text", id : tabType +"End_0", value : end, 'class' : "input-width"}).appendTo(inputGroup);
    	inputGroup.append('<span class="input-group-addon input-group-addon-r">' + nameSuffix + '</span>');
    	
    	inputGroup.appendTo(seconds2);
    	
    	return seconds2;
    }
    // 创建周期html
    function createFrequencyHtml(tabType, radioVal){
    	var name = "";
    	var frequencyName = "";
    	var start = 0;
    	if (tabType == "second") {
    		name = frequencyName = "秒";
    	} else if (tabType == "min") {
    		name = "分";
    		frequencyName = "分钟";
    	} else if (tabType == "hour") {
    		name = "点";
    		frequencyName = "小时";
    	} else if (tabType == "day") {
    		name = "号";
    		frequencyName = "天";
    		start = 1;
    	} else if (tabType == "month") {
    		name = "月";
    		frequencyName = "个月";
    		start = 1;
    	}
    	
    	var minutes3 = $("<div/>", {"class":"line"});
    	$("<input/>",{type : "radio", value : radioVal, id:tabType+"_startOn", name : tabType, 'class' : "input-radio"}).appendTo(minutes3);
    	
    	var inputGroup = $("<div/>", {"class":"input-group "});
    	inputGroup.append('<span class="input-group-addon input-group-addon-l">从</span>');
    	$("<input/>",{type : "text", id : tabType + "Start_1", value : start, 'class' : "input-width"}).appendTo(inputGroup);
    	inputGroup.append('<span class="input-group-addon">' + name + '开始到</span>');
    	$("<input/>",{type : "text", id : tabType + "End_1", value : "", 'class' : "input-width"}).appendTo(inputGroup);
    	inputGroup.append('<span class="input-group-addon input-group-addon-r">' + name + '结束</span>');
    	inputGroup.append('<span class="input-group-addon input-group-addon-l ml5">每</span>');
    	$("<input/>",{type : "text", id : tabType + "Frequency_1", value : "1", 'class' : "input-width"}).appendTo(inputGroup);
    	inputGroup.append('<span class="input-group-addon input-group-addon-r">' + frequencyName + '执行一次</span>');
    	
    	inputGroup.appendTo(minutes3);
    	
    	return minutes3;
    }
    // 创建指定 html
    function createAppointHtml(tabType, radioVal){
    	var seconds2 = $("<div/>", {"class":"line line_"+tabType+"ly "});
    	$("<input/>",{type : "radio", value : radioVal, id:tabType +"_appoint",  name : tabType, 'class' : "input-radio"}).appendTo(seconds2);
    	
    	var inputGroup = $("<div/>", {"class":"input-group "});
    	inputGroup.append('<span class="input-group-addon input-group-addon-l input-group-addon-r">指定</span>');
    	
    	var dataHtml = '<div style="float:left;" class="point_data ' + tabType + '_appoint_div">';
    	if(tabType=="second"){ //秒
    		
    		for (var i = 0; i < 60; i++) {
    			if (i%10 == 0) {
    				dataHtml +='<div class="imp secondList">';
    			}
    			//Seconds(秒)：可以用数字0-59 表示，
    			dataHtml +='<div class="cron-style"><input type="checkbox" disabled="disabled" value="'+i+'">'+("0" + i).substr(-2)+'</div>';
    			if ((i+1)%10 == 0) {
    				dataHtml +='</div>';
    			}
    		}
    	} else if (tabType=="min") { //分
    		for (var i = 0; i < 60; i++) {
            	if (i%10 == 0) {
            		dataHtml +='<div class="imp minList">';
                }
            	//Minutes(分)：可以用数字0－59 表示，
            	dataHtml +='<div class="cron-style"><input type="checkbox" disabled="disabled" value="'+i+'">'+("0" + i).substr(-2)+'</div>';
            	if ((i+1)%10 == 0) {
            		dataHtml +='</div>';
            	}
            }
    	} else if (tabType=="hour") { //时
    		for (var i = 0; i < 24; i++) {
            	if (i%10 == 0) {
            		dataHtml +='<div class="imp hourList">';
                }
            	//Hours(时)：可以用数字0-23表示,
            	dataHtml +='<div class="cron-style"><input type="checkbox" disabled="disabled" value="'+i+'">'+("0" + i).substr(-2)+'</div>';
            	if ((i+1)%10 == 0) {
            		dataHtml +='</div>';
            	}
            }
    	} else if (tabType=="day") { //天
            for (var i = 0; i < 31; i++) {
            	var dayNum = i+1;
            	if (i%10 == 0) {
            		dataHtml +='<div class="imp dayList">';
                }
            	//Day-of-Month(天)：可以用数字1-31 中的任一一个值，但要注意一些特别的月份
            	dataHtml +='<div class="cron-style"><input type="checkbox" disabled="disabled" value="'+dayNum+'">'+("0" + dayNum).substr(-2)+'</div>';
            	if ((i+1)%10 == 0) {
            		dataHtml +='</div>';
            	}
            }
    	} else if (tabType=="month") { // 月
            for (var i = 0; i < 12; i++) {
            	var monthNum = i+1;
            	if (i%10 == 0) {
            		dataHtml +='<div class="imp monthList">';
                }
            	//Month(月)：可以用1-12 或用字符串  “JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV and DEC” 表示
            	dataHtml +='<div class="cron-style"><input type="checkbox" disabled="disabled" value="'+monthNum+'">'+("0" + monthNum).substr(-2)+'</div>';
            	if ((i+1)%10 == 0) {
            		dataHtml +='</div>';
            	}
            }
    	} else if (tabType=="week") { // 周
    		var weekListHtml = '<div class="imp weekList">';
            for (var i = 0; i < 7; i++) {
            	var weekday = i+1;
            	var weekdayval = weekday;//$.fn.cronGen.tools.getWeekDayVal(weekday);
            	var weekdayLabel = "";
            	switch (weekday) {
	                case 1:
	                	weekdayLabel = "星期一";
		                break;
	                case 2:
	                	weekdayLabel = "星期二";
		                break;
	                case 3:
	                	weekdayLabel = "星期三";
		                break;
	                case 4:
	                	weekdayLabel = "星期四";
		                break;
	                case 5:
	                	weekdayLabel = "星期五";
		                break;
	                case 6:
	                	weekdayLabel = "星期六";
		                break;
	                case 7:
	                	weekdayLabel = "星期日";
		                break;
                }
            	//Day-of-Week(每周)：可以用数字1-7表示（1 ＝ 星期日,2=星期一）或用字符口串“SUN, MON, TUE, WED, THU, FRI and SAT”表示
            	weekListHtml +='<div class="cron-style weekday"><input type="checkbox" disabled="disabled" value="'+weekdayval+'">'+weekdayLabel+'</div>';
            }
            weekListHtml +='</div>';
            dataHtml += weekListHtml;
    	}
    	dataHtml +='</div>';
    	inputGroup.append(dataHtml);
    	
    	inputGroup.appendTo(seconds2);
    	
    	return seconds2;
    }
    
    // 输出值
    var generate = function () {

        var activeTab = $("ul#CronGenTabs li.active a").prop("id"); //获取当前活动页签id
        var results = "";
        switch (activeTab) {
            case "SecondlyTab":
                switch ($("input:radio[name=second]:checked").val()) {
                    case "1":
                        $.fn.cronGen.tools.everyTime("second");
                        results = $.fn.cronGen.tools.cronResult();
                        break;
                    case "2":
                        $.fn.cronGen.tools.cycle("second");
                        results = $.fn.cronGen.tools.cronResult();
                        break;
                    case "3":
                        $.fn.cronGen.tools.startOn("second");
                        results = $.fn.cronGen.tools.cronResult();
                        break;
                    case "4":
                    	$.fn.cronGen.tools.initCheckBox("second");
                        results = $.fn.cronGen.tools.cronResult();
                        break;
                }
                break;
            case "MinutesTab":
                switch ($("input:radio[name=min]:checked").val()) {
                    case "1":
                        $.fn.cronGen.tools.everyTime("min");
                        results = $.fn.cronGen.tools.cronResult();
                        break;
                    case "2":
                        $.fn.cronGen.tools.cycle("min");
                        results = $.fn.cronGen.tools.cronResult();
                        break;
                    case "3":
                        $.fn.cronGen.tools.startOn("min");
                        results = $.fn.cronGen.tools.cronResult();
                        break;
                    case "4":
                    	$.fn.cronGen.tools.initCheckBox("min");
                        results = $.fn.cronGen.tools.cronResult();
                        break;
                }
                break;
            case "HourlyTab":
                switch ($("input:radio[name=hour]:checked").val()) {
                    case "1":
                       $.fn.cronGen.tools.everyTime("hour");
                        results = $.fn.cronGen.tools.cronResult();
                        break;
                    case "2":
                       $.fn.cronGen.tools.cycle("hour");
                        results = $.fn.cronGen.tools.cronResult();
                        break;
                    case "3":
                        $.fn.cronGen.tools.startOn("hour");
                        results = $.fn.cronGen.tools.cronResult();
                        break;
                    case "4":
                    	$.fn.cronGen.tools.initCheckBox("hour");
                        results = $.fn.cronGen.tools.cronResult();
                        break;
                }
                break;
            case "DailyTab":
                switch ($("input:radio[name=day]:checked").val()) {
                    case "1":
                        $.fn.cronGen.tools.everyTime("day");
                        results = $.fn.cronGen.tools.cronResult();
                        break;
                    case "2":
                        $.fn.cronGen.tools.unAppoint("day");
                        results = $.fn.cronGen.tools.cronResult();
                        break;
                    case "3":
                        $.fn.cronGen.tools.cycle("day");
                        results = $.fn.cronGen.tools.cronResult();
                        break;
                    case "4":
                        $.fn.cronGen.tools.startOn("day");
                        results = $.fn.cronGen.tools.cronResult();
                        break;
                    case "5":
                        $.fn.cronGen.tools.workDay("day");
                        results = $.fn.cronGen.tools.cronResult();
                        break;
                    case "6":
                        $.fn.cronGen.tools.lastDay("day"); //每月最后一天
                        results = $.fn.cronGen.tools.cronResult();
                        break;
					case "8":
                        $.fn.cronGen.tools.lastWorkDay("day"); //每月最后一个工作日
                        results = $.fn.cronGen.tools.cronResult();
                        break;
                    case "7":
                    	$.fn.cronGen.tools.initCheckBox("day");
                        results = $.fn.cronGen.tools.cronResult();
                        break;
                }
                break;
            case "MonthlyTab":
                switch ($("input:radio[name=month]:checked").val()) {
                    case "1":
                        $.fn.cronGen.tools.everyTime("month");
                        results = $.fn.cronGen.tools.cronResult();
                        break;
                    case "2":
                        $.fn.cronGen.tools.unAppoint("month");
                        results = $.fn.cronGen.tools.cronResult();
                        break;
                    case "3":
                        $.fn.cronGen.tools.cycle("month");
                        results = $.fn.cronGen.tools.cronResult();
                        break;
                    case "4":
                        $.fn.cronGen.tools.startOn("month");
                        results = $.fn.cronGen.tools.cronResult();
                        break;
                    case "5":
                    	$.fn.cronGen.tools.initCheckBox("month");
                        results = $.fn.cronGen.tools.cronResult();
                        break;
                }
                break;
            case "WeeklyTab":
                switch ($("input:radio[name=week]:checked").val()) {
                    case "1":
                        $.fn.cronGen.tools.everyTime("week");
                        results = $.fn.cronGen.tools.cronResult();
                        break;
                    case "2":
                        $.fn.cronGen.tools.unAppoint("week");
                        results = $.fn.cronGen.tools.cronResult();
                        break;
                    case "3":
                        $.fn.cronGen.tools.cycle("week");
                        results = $.fn.cronGen.tools.cronResult();
                        break;
                    case "4":
                        $.fn.cronGen.tools.weekOfDay("week");
                        results = $.fn.cronGen.tools.cronResult();
                        break;
                    case "5":
                        $.fn.cronGen.tools.lastWeek("week");
                        results = $.fn.cronGen.tools.cronResult();
                        break;
                    case "6":
                    	$.fn.cronGen.tools.initCheckBox("week");
                        results = $.fn.cronGen.tools.cronResult();
                        break;
                }
                break;
            case "YearlyTab":
                switch ($("input:radio[name=year]:checked").val()) {
                    case "1":
                        $.fn.cronGen.tools.unAppoint("year");
                        results = $.fn.cronGen.tools.cronResult();
                        break;
                    case "2":
                        $.fn.cronGen.tools.everyTime("year");
                        results = $.fn.cronGen.tools.cronResult();
                        break;
                    case "3":
                        $.fn.cronGen.tools.cycle("year");
                        results = $.fn.cronGen.tools.cronResult();
                        break;
                }
                break;
        }
        // Update display
        valueShowElement.val(results).triggerHandler("change");
        
        console.log("val==="+valueShowElement.val());
    };

    
    $.fn.cronGen.tools = {
		//转换为星期对应的值，根据input转换为表达式用 quartz Day-of-Week(每周)：可以用数字1-7表示（1 ＝ 星期日,2=星期一）或用字符串“SUN, MON, TUE, WED, THU, FRI and SAT”表示
		getWeekDayVal : function (weekday) {
			var type = $("input[name='CronGenTypeInput']:checked").val();
	    	var isQuartz = type == type_quartz; //quartz转换
	    	if (isQuartz) { // quartz 星期一的值2，星期天值为1
	    		weekday = parseInt(weekday);
	    		var weekdayval = weekday+1;
	    		if (weekday == 7) { // 星期天为1
	    			weekdayval = 1;
	    		}
	    		return weekdayval;
	    	}
	    	return weekday;
	    },
	    //根据对应值返回星期数 quartz值1返回7（星期日）2返回1（星期一）,选中input时用
	    getWeekDay : function (weekdayval) {
	    	var type = $("input[name='CronGenTypeInput']:checked").val();
			var isQuartz = type == type_quartz; //quartz转换,
			if(isNaN(parseInt(weekdayval))){ //非数字
				
				weekdayval = weekdayval.toLowerCase();
				if(weekdayval=='mon'){
					weekdayval = '1';
				} else if(weekdayval=='mon'){
					weekdayval = '2';
				} else if(weekdayval=='wed'){
					weekdayval = '3';
				} else if(weekdayval=='thu'){
					weekdayval = '4';
				} else if(weekdayval=='fri'){
					weekdayval = '5';
				} else if(weekdayval=='sat'){
					weekdayval = '6';
				} else if(weekdayval=='sun'){
					weekdayval = '7';
				}
				if (isQuartz) { // quartz允许全称
					if(weekdayval=='monday'){
					weekdayval = '1';
					} else if(weekdayval=='tuesday'){
						weekdayval = '2';
					} else if( weekdayval=='wednesday'){
						weekdayval = '3';
					} else if(weekdayval=='thursday'){
						weekdayval = '4';
					} else if(weekdayval=='friday'){
						weekdayval = '5';
					} else if(weekdayval=='saturday'){
						weekdayval = '6';
					} else if(weekdayval=='sunday'){
						weekdayval = '7';
					}
				}	

			} else {
				if (isQuartz) {
					weekdayval = parseInt(weekdayval);
					var weekday = weekdayval - 1;
					if (weekday == 0) {
						weekday = 7;
					}
					return weekday;
				} else if (weekday == 0) { // 0=7 代表星期天
					weekday = 7;
				}
			}
						
	    	return weekdayval;
	    },
        /**
         * 每周期
         */
        everyTime : function(dom){
            $("#"+dom+"Hidden").val("*");
            $.fn.cronGen.tools.clearCheckbox(dom);
        },
        /**
         * 不指定
         */
        unAppoint : function(dom){
            var val = "?";
            if (dom == "year")
            {
                val = "";
            }
            $("#"+dom+"Hidden").val(val);
            $.fn.cronGen.tools.clearCheckbox(dom);
        },
        /**
         * 周期
         */
        cycle : function(dom, parse){
        	if (parse == null) {
        		parse = true;
            }
            var start = $("#"+dom+"Start_0").val();
            var end = $("#"+dom+"End_0").val();
            if (dom=='week' && parse) {
            	start = this.getWeekDayVal(start);
            	end = this.getWeekDayVal(end);
            } 
            $("#"+dom+"Hidden").val(start + "-" + end);
            $.fn.cronGen.tools.clearCheckbox(dom);
        },
        /**
         * 从开始
         */
        startOn : function(dom) {
            var start = $("#"+dom+"Start_1").val();
            var end = $("#"+dom+"End_1").val();
            var frequency = $("#"+dom+"Frequency_1").val();
            var val = start;
            if (end) {
            	val += "-"+ end;
            }
            if (frequency) {
            	frequency = "/" + frequency;
            }
            $("#"+dom+"Hidden").val(val + frequency);
            $.fn.cronGen.tools.clearCheckbox(dom);
        },
        /**
         * 每月最后一天
         */
        lastDay : function(dom){
            $("#"+dom+"Hidden").val("L");
            $.fn.cronGen.tools.clearCheckbox(dom);
        },
		lastWorkDay : function(dom){
            $("#"+dom+"Hidden").val("LW");
            $.fn.cronGen.tools.clearCheckbox(dom);
        },
        /**
         * 第x个星期x
         */
        weekOfDay : function(dom){
            var start = $("#"+dom+"Start_1").val();
            var end = $("#"+dom+"End_1").val(); 
            $("#"+dom+"Hidden").val(this.getWeekDayVal(end) + "#" + start ); //6#3" or "FRI#3"指这个月第3个周五(6指周五，3指第3个)
            $.fn.cronGen.tools.clearCheckbox(dom);
        },
        /**
         * 最后一个周x
         */
        lastWeek : function(dom){
            var start = $("#"+dom+"Start_2").val();
            $("#"+dom+"Hidden").val(this.getWeekDayVal(start)+"L");
            $.fn.cronGen.tools.clearCheckbox(dom);
        },
        /**
         * 工作日
         */
        workDay : function(dom) {
            var start = $("#"+dom+"Start_2").val();
            $("#"+dom+"Hidden").val(start + "W");
            $.fn.cronGen.tools.clearCheckbox(dom);
        },
        // 指定  日期input的点击操作事件
        initChangeEvent : function(){
            var secondList = $(".secondList").children().find(":checkbox");
            $("#second_appoint").click(function(){
                if (this.checked) {
                    if (secondList.filter(":checked").length == 0) {
                        secondList.eq(0).prop("checked", true);
                    }
                    secondList.eq(0).change();
                }
            });
        
            secondList.change(function() {
                var second_appoint = $("#second_appoint").prop("checked");
                if (second_appoint) {
                    var vals = [];
                    secondList.each(function() {
                        if (this.checked) {
                            vals.push(this.value);
                        }
                    });
                    var val = "?";
                    if (vals.length > 0 && vals.length < 59) {
                        val = vals.join(","); 
                    }else if(vals.length == 59){
                        val = "*";
                    }
                    $("#secondHidden").val(val);
                }
            });
            
            var minList = $(".minList").children().find(":checkbox");
            $("#min_appoint").click(function(){
                if (this.checked) {
                    if (minList.filter(":checked").length == 0) {
                        minList.eq(0).prop("checked", true);
                    }
                    minList.eq(0).change();
                }
            });
            
            minList.change(function() {
                var min_appoint = $("#min_appoint").prop("checked");
                if (min_appoint) {
                    var vals = [];
                    minList.each(function() {
                        if (this.checked) {
                            vals.push(this.value);
                        }
                    });
                    var val = "?";
                    if (vals.length > 0 && vals.length < 59) {
                        val = vals.join(",");
                    }else if(vals.length == 59){
                        val = "*";
                    }
                    $("#minHidden").val(val);
                }
            });
            
            var hourList = $(".hourList").children().find(":checkbox");
            $("#hour_appoint").click(function(){
                if (this.checked) {
                    if (hourList.filter(":checked").length == 0) {
                        hourList.eq(0).prop("checked", true);
                    }
                    hourList.eq(0).change();
                }
            });
            
            hourList.change(function() {
                var hour_appoint = $("#hour_appoint").prop("checked");
                if (hour_appoint) {
                    var vals = [];
                    hourList.each(function() {
                        if (this.checked) {
                            vals.push(this.value);
                        }
                    });
                    var val = "?";
                    if (vals.length > 0 && vals.length < 24) {
                        val = vals.join(",");
                    }else if(vals.length == 24){
                        val = "*";
                    }
                    $("#hourHidden").val(val);
                }
            });
            
            var dayList = $(".dayList").children().find(":checkbox");
            $("#day_appoint").click(function(){
                if (this.checked) {
                    if (dayList.filter(":checked").length == 0) {
                        dayList.eq(0).prop("checked", true);
                    }
                    dayList.eq(0).change();
                }
            });
            
            dayList.change(function() {
                var day_appoint = $("#day_appoint").prop("checked");
                if (day_appoint) {
                    var vals = [];
                    dayList.each(function() {
                        if (this.checked) {
                            vals.push(this.value);
                        }
                    });
                    var val = "?";
                    if (vals.length > 0 && vals.length < 31) {
                        val = vals.join(",");
                    }else if(vals.length == 31){
                        val = "*";
                    }
                   $("#dayHidden").val(val);
                }
            });
            
            var monthList = $(".monthList").children().find(":checkbox");
            $("#month_appoint").click(function(){
                if (this.checked) {
                    if (monthList.filter(":checked").length == 0) {
                        monthList.eq(0).prop("checked", true);
                    }
                    monthList.eq(0).change();
                }
            });
            
            monthList.change(function() {
                var month_appoint = $("#month_appoint").prop("checked");
                if (month_appoint) {
                    var vals = [];
                    monthList.each(function() {
                        if (this.checked) {
                            vals.push(this.value);
                        }
                    });
                    var val = "?";
                    if (vals.length > 0 && vals.length < 12) {
                        val = vals.join(",");
                    } else if(vals.length == 12){ // 12个月全
                        val = "*";
                    }
                    $("#monthHidden").val(val);
                }
            });
            
            var weekList = $(".weekList").children().find(":checkbox");
            $("#week_appoint").click(function(){
                if (this.checked) {
                    if (weekList.filter(":checked").length == 0) {
                        weekList.eq(0).prop("checked", true);
                    }
                    weekList.eq(0).change();
                }
            });
			// 获取星期
            var getWeekDayVal = this.getWeekDayVal;
            weekList.change(function() {
                var week_appoint = $("#week_appoint").prop("checked");
				
                if (week_appoint) {
                    var vals = [];
                    weekList.each(function() {
                        if (this.checked) {
							var value = getWeekDayVal(this.value);
                            vals.push(value);
                        }
                    });
                    var val = "?";
                    if (vals.length > 0 && vals.length < 7) {
                        val = vals.join(",");						
                    } else if(vals.length == 7){ // 全选上了
                        val = "*";
                    }
                   $("#weekHidden").val(val);
                }
            });
        },
        //时分秒 cron表达式转换为input的值
        initObj : function(strVal, strid){ 
            var ary = null;
            if (strVal) {
            	if (strVal == "*") { //每 时分秒
            		$("#" + strid + "_everyTime").prop("checked", true);
            	} else if (strVal.indexOf('-') != -1 || strVal.indexOf('/') != -1 ) { //范围
            		var start = strVal, end="", frequency="";
            		
            		if (strVal.indexOf('/') != -1 ) { //周期
                		ary = strVal.split('/');
                		frequency = ary[1];
                		start = ary[0];
                	} 
            		if (start.indexOf('-') != -1 ) { //范围
                		ary = start.split('-');
                		start = ary[0];
                		end = ary[1];
                	}
					// 清除原来的值
					$("#" + strid + "Start_1").val('');
                	$("#" + strid + "End_1").val('');
					$("#" + strid + "Start_0").val('');
                	$("#" + strid + "End_0").val('');
					
            		if (strVal.indexOf('/') != -1 ) { //周期
                		$("#" + strid + "_startOn").prop("checked", true);
                		$("#" + strid + "Start_1").val(start);
                		$("#" + strid + "End_1").val(end);
                		$("#" + strid + "Frequency_1").val(frequency);
                	} else if (strVal.indexOf('-') != -1 ) { //范围
                		$("#" + strid + "_cycle").prop("checked", true);
                		$("#" + strid + "Start_0").val(start);
                		$("#" + strid + "End_0").val(end);
                	} 
            	} else { //指定
            		$("#" + strid + "_appoint").prop("checked", true);
            		if (strVal != "?") {
            			ary = strVal.split(",");
						// 清除原来的选中
						$("." + strid + "List :input").prop("checked", false);
            			for (var i = 0; i < ary.length; i++) {
							// 周，quartz需要特殊处理
							var value = ary[i];
							if (strid=='week') {
								value = $.fn.cronGen.tools.getWeekDay(value);
							} 
            				$("." + strid + "List :input[value='" + value + "']").prop("checked", true);
            			}
            			$.fn.cronGen.tools.initCheckBox(strid);
            		}
            	}
            }
        },
        // 天 cron表达式转换为input的值
        initDay : function(strVal) {
            var ary = null;
			// 清除原来的值
			$("#dayStart_2").val('');
			
            if (strVal == "?") { //不指定
            	$("#day_unAppoint").prop("checked", true);
            } else if (strVal == "LW") { //每月最后一个工作日
            	$("#day_lastWorkDay").prop("checked", true);
            } else if (strVal.split('W').length > 1) { //每月 x号最近的那个工作日
                ary = strVal.split('W');
                $("#day_workDay").prop("checked", true);
                $("#dayStart_2").val(ary[0]);
            } else if (strVal == "L") { //每月最后一天
            	$("#day_lastDay").prop("checked", true);
            } else { //每天 或 范围 或 周期 等其他的
        		this.initObj(strVal, "day")
        	} 
        },
        initMonth : function(strVal) {
            if (strVal == "?") { //不指定
            	$("#month_unAppoint").prop("checked", true);
            } else { //每天 或 范围 或 周期 等其他的
        		this.initObj(strVal, "month")
        	}
        },
        initWeek : function(strVal) {
            var ary = null;
			// 清除原来的值
			$("#weekStart_1").val('');
			$("#weekStart_2").val('');
			
            if (strVal == "?") { //不指定
            	$("#week_unAppoint").prop("checked", true);
            } else if (strVal.split('#').length > 1) { //第x个周x
                ary = strVal.split('#');
                $("#week_weekOfDay").prop("checked", true);
                $("#weekStart_1").val(ary[1]);
                $("#weekEnd_1").val(this.getWeekDay(ary[0]));
            } else if (strVal.split('L').length > 1) { //每月最后一个周x
                ary = strVal.split('L');
                $("#week_lastWeek").prop("checked", true);
                $("#weekStart_2").val(this.getWeekDay(ary[0]));
            } else { //每天 或 范围 或 周期 等其他的
        		this.initObj(strVal, "week")
        	}
        },
        // 年赋值
        initYear : function(strVal) {
            this.initObj(strVal, "year")
        },
        //将表单式的值转换为input对应的数值
        cronParse : function(cronExpress) {
            if (cronExpress) {
                var regs = cronExpress.split(' ');
                $("#secondHidden").val(regs[0]);
                $("#minHidden").val(regs[1]);
                $("#hourHidden").val(regs[2]);
                $("#dayHidden").val(regs[3]);
                $("#monthHidden").val(regs[4]);
                $("#weekHidden").val(regs[5]);

                $.fn.cronGen.tools.initObj(regs[0], "second");
                $.fn.cronGen.tools.initObj(regs[1], "min");
                $.fn.cronGen.tools.initObj(regs[2], "hour");
                $.fn.cronGen.tools.initDay(regs[3]);
                $.fn.cronGen.tools.initMonth(regs[4]);
                $.fn.cronGen.tools.initWeek(regs[5]);

                if (regs.length > 6) {
                    $("#yearHidden").val(regs[6]);
                    $.fn.cronGen.tools.initYear(regs[6]);
                }
            }
    	},
    	// 更改input的值输出cron表达式
        cronResult : function() {
            var result;
            var second = $("#secondHidden").val();
            second = second== "" ? "*":second;
            var minute = $("#minHidden").val();
            minute = minute== "" ? "*":minute;
            var hour = $("#hourHidden").val();
            hour = hour== "" ? "*":hour;
            var day = $("#dayHidden").val();
            day = day== "" ? "*":day;
            var month = $("#monthHidden").val();
            month = month== "" ? "*":month;
            var week = $("#weekHidden").val();
            week = week== "" ? "?":week;
            
            // 周数值 处理
	    	if (week.indexOf(",")!=-1) {
	    		var type = $("input[name='CronGenTypeInput']:checked").val();
	    		var parse = type == type_quartz; //quartz转换
		    	if (parse) {
		    		var vals = [];
	                
		    		var ary = week.split(",");
	    			for (var i = 0; i < ary.length; i++) {
	    				var weekday = parseInt(ary[i]);
	    				var weekdayval = weekday+1;
	    				if (weekday == 7) {
	    					weekdayval = 1;
	    				}
	    				vals.push(weekdayval);
	    			}
	    			var val = vals.join(",");
	    			week = val;
		    	}
	    	}
            
            var year = $("#yearHidden").val();
            var item = [];
            item.push(second);
            item.push(minute);
            item.push(hour);
            item.push(day);
            item.push(month);
            item.push(week);
            var type = $("input[name='CronGenTypeInput']:checked").val();
	    	var isQuartz = type == type_quartz; //quartz转换
            if (year!="" && isQuartz) { //只有quartz有年
                item.push(year);
            }
            //修复表达式错误BUG，如果后一项不为* 那么前一项肯定不为*，要不然就成了每秒执行了
            //获取当前选中tab
            var currentIndex = $("#CronGenTabs li.active").index();
            //当前选中项之前的如果为*，则都设置成0
            for (var i = currentIndex; i >= 1; i--) {
            	if (item[i] != "*" && item[i - 1] == "*") {
            		if ( i-1 == 5) { //周，只能为?
            			item[i - 1] = "?";
            		} else {
            			item[i - 1] = "0";
            		}
            	}
            }
            //当前选中项之后的如果不为*则都设置成*
            if (item[currentIndex] == "*") {
            	for (var i = currentIndex + 1; i < item.length; i++) {
            		if (i == 5) { //周，只能为?
            			item[i] = "?";
            		} else {
            			item[i] = "*";
            		}
            	}
            }
            if (item[5] != "?") { //Day-of-Month和Day-of-Week中，指“没有具体的值”。当两个子表达式其中一个被指定了值以后，为了避免冲突，需要将另外一个的值设为“?”
            	item[3] = "?";
            	if (item[4] == "0") {
                	item[4] = "*";
                }
            }
            if (item[3] == "0") { //Day-of-Month和Day-of-Week中，指“没有具体的值”。当两个子表达式其中一个被指定了值以后，为了避免冲突，需要将另外一个的值设为“?”
            	item[3] = "?";
            }
            if (item[4] == "0") { //月
            	item[4] = "*";
            }
            if (item[3] == "?" && item[5] == "?") { //只能有一个
            	item[3] = "*";
            }
            result =item.join(" ");
            return result;
        },
        // cron表达式解释为字符串
        explainCron : function(value) {
        	var vals = value.replace(/  /g," ").split(" ");
        	var showHtml = "";
        	if (vals.length >= 6) {
                var secondVal = vals[0];
                var minuteVal = vals[1];
                var hourVal = vals[2];
                var dayOfMonthVal = vals[3];
                var monthVal = vals[4];
                var dayOfWeekVal = vals[5];
                var yearVal;
                if (vals.length >= 7) {
                	yearVal = vals[6];
                }
                if (yearVal) {
                    if (yearVal == "*") {
                    	showHtml += "每年";
                    } else {
                    	showHtml += yearVal+"年";
                    }
                }
                if (monthVal) {
                	if (monthVal == "*") {
                		showHtml += "每月";
                	} else if (monthVal == "?") {
                		showHtml += "";
                	} else if (monthVal.indexOf('/')!=-1 || monthVal.indexOf('-')!=-1) {
                    	var frequency = "";
                    	if (monthVal.split('/').length > 1) { //周期
                    		var ary = monthVal.split('/');
                    		monthVal = ary[0];
                    		frequency = "每" + ary[1] + "个月";
                    	}
                    	if (monthVal.split('-').length > 1) { //范围
                            var ary = monthVal.split('-');
                            showHtml += "从"+ ary[0] + "月到" + ary[1] + "月"+frequency;
                        } else {
                        	showHtml += "从"+ monthVal + "月开始"+frequency;
                        }
                    } else {
                		var ary = monthVal.split(","); //指定时间
                		for (var i = 0; i < ary.length; i++) {
                			showHtml += ary[i] + "月";
                		}
                	}
                }
                if (dayOfWeekVal) {
                    if (dayOfWeekVal == "*") {
                    	showHtml += "每周";
                    } else if (dayOfWeekVal == "?") {
                    	showHtml += "";
                    } else if (dayOfWeekVal.split('-').length > 1) { //范围
                        var ary = dayOfWeekVal.split('-');
                        showHtml += "星期" + $.fn.cronGen.tools.getWeekDay(ary[0]) + "到星期" + $.fn.cronGen.tools.getWeekDay(ary[1]) + " ";
                    } else if (dayOfWeekVal.split('#').length > 1) { //第x个周x
                    	var ary = dayOfWeekVal.split('#'); //第一个为周x第二个为第x个
                        showHtml += "第" + ary[1] + "个星期" + $.fn.cronGen.tools.getWeekDay(ary[0]) + " ";
                    } else if (dayOfWeekVal.split('L').length > 1) { //每月最后一个周x
                    	var ary = dayOfWeekVal.split('L');
                    	showHtml += "最后一个星期" + $.fn.cronGen.tools.getWeekDay(ary[0]) + " ";
                    } else {
                    	var ary = dayOfWeekVal.split(",");
                    	for (var i = 0; i < ary.length; i++) {
                            showHtml += "星期" + $.fn.cronGen.tools.getWeekDay(ary[i]) + " ";
                        }
                    }
                }
                if (dayOfMonthVal) {
                    if (dayOfMonthVal == "*") {
                    	showHtml += "每天";
                    } else if (dayOfMonthVal == "?") {
                    	showHtml += "";
                    } else if (dayOfMonthVal == 'LW') { //每月最后一个工作日
                    	showHtml += "最后一个工作日";
                    } else if (dayOfMonthVal.split('W').length > 1) { //x号最近的那个工作日
                    	var ary = dayOfMonthVal.split('W'); //第一个为周x第二个为第x个
                        showHtml += ary[0] + "号最近的工作日";
                    } else if (dayOfMonthVal.split('L').length > 1) { //每月最后一天
                    	showHtml += "最后一天";
                    } else if (dayOfMonthVal.indexOf('/')!=-1 || dayOfMonthVal.indexOf('-')!=-1) {
                    	var frequency = "";
                    	if (dayOfMonthVal.split('/').length > 1) { //周期
                    		var ary = dayOfMonthVal.split('/');
                    		dayOfMonthVal = ary[0];
                    		frequency = "每" + ary[1] + "天";
                    	}
                    	if (dayOfMonthVal.split('-').length > 1) { //范围
                            var ary = dayOfMonthVal.split('-');
                            showHtml += "从"+ ary[0] + "号到" + ary[1] + "号"+frequency;
                        } else {
                        	showHtml += "从"+ dayOfMonthVal + "号开始"+frequency;
                        }
                    } else { 
                    	var ary = dayOfMonthVal.split(","); //指定时间
                    	for (var i = 0; i < ary.length; i++) {
                            showHtml += ary[i]+"号";
                        }
                    } 
                }
                if (hourVal) {
                    if (hourVal == "*") {
                    	showHtml += "每小时";
                    } else if (hourVal.indexOf('/')!=-1 || hourVal.indexOf('-')!=-1) {
                    	var frequency = "";
                    	if (hourVal.split('/').length > 1) { //周期
                    		var ary = hourVal.split('/');
                    		hourVal = ary[0];
                    		frequency = "每" + ary[1] + "个小时";
                    	}
                    	if (hourVal.split('-').length > 1) { //范围
                            var ary = hourVal.split('-');
                            showHtml += "从"+ ary[0] + "点到" + ary[1] + "点"+frequency;
                        } else {
                        	showHtml += "从"+ hourVal + "点开始"+frequency;
                        }
                    } else { 
                    	var ary = hourVal.split(","); //指定时间
                    	for (var i = 0; i < ary.length; i++) {
                            showHtml += ary[i]+"点";
                        }
                    } 
                }
                if (minuteVal) {
                    if (minuteVal == "*") {
                    	showHtml += "每分钟";
                    } else if (minuteVal.indexOf('/')!=-1 || minuteVal.indexOf('-')!=-1) {
                    	var frequency = "";
                    	if (minuteVal.split('/').length > 1) { //周期
                    		var ary = minuteVal.split('/');
                    		minuteVal = ary[0];
                    		frequency = "每" + ary[1] + "分钟";
                    	}
                    	if (minuteVal.split('-').length > 1) { //范围
                            var ary = minuteVal.split('-');
                            showHtml += "从"+ ary[0] + "分到" + ary[1] + "分"+frequency;
                        } else {
                        	showHtml += "从"+ minuteVal + "分开始"+frequency;
                        }
                    } else { 
                    	var ary = minuteVal.split(","); //指定时间
                    	for (var i = 0; i < ary.length; i++) {
                            showHtml += ary[i] + "分";
                        }
                    } 
                }
                if (secondVal) {
                    if (secondVal == "*") {
                    	showHtml += "每秒";
                    } else if (secondVal.indexOf('/')!=-1 || secondVal.indexOf('-')!=-1) {
                    	var frequency = "";
                    	if (secondVal.split('/').length > 1) { //周期
                    		var ary = secondVal.split('/');
                    		secondVal = ary[0];
                    		frequency = "每" + ary[1] + "秒";
                    	}
                    	if (secondVal.split('-').length > 1) { //范围
                            var ary = secondVal.split('-');
                            showHtml += "从"+ ary[0] + "秒到" + ary[1] + "秒"+frequency;
                        } else {
                        	showHtml += "从"+ secondVal + "秒开始"+frequency;
                        }
                    } else { 
                    	var ary = secondVal.split(","); //指定时间
                    	for (var i = 0; i < ary.length; i++) {
                            showHtml += ary[i] + "秒";
                        }
                    }
                }
                
                showHtml = showHtml.replace("每年每月","每月").replace("每月每天","每天").replace("每天每小时","每小时").
                	replace("每月每周","每周").replace("每周每小时","每小时").replace("每小时每分钟","每分钟").replace("每分钟每秒","每秒");
                
            }
        	return showHtml;
        },
        //指定日期时用，清除选中的checkbox值
        clearCheckbox : function(dom){
            var list = $("."+dom+"List").find(":checkbox").filter(":checked");
            if ($(list).length > 0) {
            	$.each(list, function(index){
            		$(this).prop("checked", false);
            		$(this).prop("disabled", true);
            		$(this).change();
            	});
            }
            $("."+dom+"List").find(":checkbox").prop("disabled", true);
        },
        //指定日期时用，移除checkbox的禁用
        initCheckBox : function(dom) {
            var list = $("."+dom+"List").children().find(":input");
            if (list.length > 0) {
            	$.each(list, function(){
            		$(this).prop("disabled", false);
            	});
            }
        }
    };
    
    //默认参数
    $.fn.cronGen.defaultOptions = {
		//类型，quartz和springcron两种
        type : 'quartz'
        //是否显示类型选择
        ,showtype : true
        //确定按钮样式
        ,submitBtnClass : 'shield-btn'
        ,showInputClass : 'shield-input'
        ,inputGroupBtnStyle : 'float:left;'
        //选择按钮html
        ,selectBtn : '<button class="shield-btn shield-btn-primary shield-btn-small"><i class="shield-icon">&#xe6f4;</i></button>'
    };
})(jQuery);
